#!/bin/bash -e

usage() {
  echo "usage: $0 COMMON_NAME [OUT]"
  echo
  echo "  COMMON_NAME   the domain name the certificate is valid for, eg. example.com"
  echo "  OUT           path to output directory generated files will be placed in"
  echo
}

if [ -z "$1" ]; then
  usage
  exit 1
fi

CMD="$(realpath "$0")"
DIR="$(dirname "${CMD}")"

CN="$1"
OUT="$(realpath "${2:-.}")"

# shellcheck source=scripts/ssl-common.sh
source "${DIR}/ssl-common.sh"

VPN_PKI="$(realpath "${OUT}/vpn")"
VPN_CA="${VPN_PKI}/ca.crt"
VPN_CRT="${VPN_PKI}/issued/vpn.${CN}.crt"
VPN_KEY="${VPN_PKI}/private/vpn.${CN}.key"
VPN_DH="${VPN_PKI}/dh.pem"

if [ ! -f $VPN_CA ] || [ ! -f $VPN_CRT ] || [ ! -f $VPN_KEY ] || [ ! -f $VPN_DH ]; then

  rm -f $VPN_CA $VPN_CRT $VPN_DH $VPN_KEY

  # generate VPN CA
  "$easyrsa_bin" --pki-dir="${VPN_PKI}" init-pki &>/dev/null
  "$easyrsa_bin" --pki-dir="${VPN_PKI}" --days="${CA_EXPIRY_DAYS}" --req-cn="vpn-ca.${CN}" build-ca nopass 2>/dev/null

  # generate and sign vpn server certificate
  "$easyrsa_bin" --pki-dir="${VPN_PKI}" --days="${CRT_EXPIRY_DAYS}" build-server-full "vpn.${CN}" nopass 2>/dev/null

  # generate vpn dhparams (keysize of 2048 will do, 4096 can wind up taking hours to generate)
  "$easyrsa_bin" --pki-dir="${VPN_PKI}" --keysize=2048 gen-dh 2>/dev/null

  # update indexes and generate CRLs
  "$easyrsa_bin" --pki-dir="${VPN_PKI}" update-db 2>/dev/null
  "$easyrsa_bin" --pki-dir="${VPN_PKI}" gen-crl 2>/dev/null
fi